package dp;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author lushiliang
 */
public class leetCode95_GenerateTrees2 {


    public List<TreeNode> generateTrees(int n) {
        return generateTrees(1, n);
    }

    private List<TreeNode> generateTrees(int start, int end) {
        List<TreeNode> result = new LinkedList<>();

        if(start > end){
            result.add(null);
            return result;
        }
        for (int i = start; i <= end; i++) {
            List<TreeNode> left = generateTrees(start,i-1);
            List<TreeNode> right = generateTrees(i + 1,end);

            for (TreeNode lTreeNode : left) {
                for (TreeNode rTreeNode : right) {
                    result.add(new TreeNode(i,lTreeNode,rTreeNode));
                }
            }
        }
        return result;
    }

    public static class TreeNode { int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }}

}
